<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
use Crypt;
use Cookie;
class LoginController extends Controller
{
    //login
    public function login(Request $request)
    {
    	if($request -> isMethod('POST'))
    	{
    		$isLogin = \Cookie::get('isLogin');
    		if($isLogin)
    		{
    			$res = DB::table('users as u1')
                     -> select('u1.*','info.pic')
                     -> leftjoin('users_info as info','u1.id','=','info.user_id')
                     -> where('email', $isLogin)
                     -> first();
    			Session::put('master', $res);
    			return redirect('/admin/index') -> with(['info' => '登录成功']);
    		}

    		$request -> flashOnly('email');
    		$code = $request -> input('code');
    		if($code != Session::get('code'))
    		{
    			return back() -> with(['info' => '验证码错误']);
    		}
    		// 验证邮箱和密码
    		$email = $request -> input('email');
    		$res = DB::table('users') -> where('email', $email) -> first();
    		if(!$res)
    		{
    			return back() -> with(['info' => '用户名未注册']);
    		}
    		// 解密
    		$password = Crypt::decryptString($res -> password);
    		if($request -> input('password') != $password)
    		{
    			return back() -> with(['info' => '用户名或者密码错误']);
    		}
    		// 判断是否记住我
    		if($request -> has('checkMe'))
    		{
    			\Cookie::queue('isLogin', $res -> email, 60 * 24 * 7);
    		}

    		Session::put('master', $res);
    		return redirect('/admin/index') -> with(['info' => '登录成功']);
    	}else
    	{
    		return view('admin.login.index', ['title' => '登陆']);
    	}
    }

    public function logout()
    {
    	Session::forget('master');
    	return redirect('/admin/login') -> with(['info' => '登出成功']);
    }
}
